def flatten(an_iter):
    # self is the visitor, p is the visited
    next_iters = [an_iter]
    while len(next_iters) > 0:
        push_it = False
        pushed = []
        for value in next_iters.pop(0):
            if push_it:
                # group remaining elements
                pushed.append(value)
            elif hasattr(value, "__iter__"):
                # the value is iterable, iterate it first
                next_iters.insert(0, value)
                # group the remaining elements in a list
                push_it = True
            else:
                # simpler case
                yield value
        
        # move the elements pushed into the next_iters
        if len(pushed) > 0:
            next_iters.insert(1, pushed)

v = 1

for x in range(1000000):
    v = (v,)
    

for v in flatten((1,2,(3,), v)):
    print v
